/// <reference path="jquery-latest.js" />

(function($){
	$.jTagging = function(obj, options){
		normalStyle = options.style.normalStyle;
		selectedStyle = options.style.selectedStyle;
		normalHoverStyle = options.style.normalHoverStyle;
		
		var eventList = new Array("keydown", "keyup");
		this.tags = $(options.tags).find("a");
		this.input = obj;
		this.obj = obj;
		this.options = options;
		var owner = this;
		$.each(eventList, function(i, e){
			//bind input event
			$(obj).bind(e, function(){
				owner.flagTags(true);

			});
		});
		this.flagTags(true);
	}
    $.jTagging.defaults = {
	
		normalStyle: {
			padding: "2px 1px 0 1px",
			textDecoration: "none",
			color: "#6665cb",
			backgroundColor: ""
		},
		selectedStyle: {
			padding: "2px 1px 0 1px",
			textDecoration: "none",
			color: "#fff",
			backgroundColor: "#6665cb"
		},
		normalHoverStyle: {
			padding: "2px 1px 0 1px",
			textDecoration: "none",
			color: "#fff",
			backgroundColor: "#6665cb"
		}
	}
	$.jTagging.prototype = {
		arrayRemove: function(array, value){
			array = array || [];
			for (var o in array) {
				array[o] = $.trim(array[o]);
				if (array[o] == value || array[o] == "") {
					array.splice(o, 1);
				}
			}
			
		},
		setClass: function(el, nc, hc){
			$(el).css(nc);
			$(el).hover(function(){
				$(el).css(hc);
			}, function(){
				$(el).css(nc);
			});
		},
		flagTags: function(bindclick){
			var input = this.obj;
			var options = this.options;
			var style = options.style;
			var owner = this;
			var inputValueArray = $(input).val().split(options.seperator);
			this.arrayRemove(inputValueArray);
			this.tags.each(function(){
			
				if ($(inputValueArray).index($(this).text()) >= 0) {
					owner.setClass(this, style.selectedStyle, style.normalHoverStyle);
				}
				else {
					owner.setClass(this, style.normalStyle, style.normalHoverStyle);
				}
				if (bindclick) {
					$(this).removeClass();
					$(this).attr("href", "#");
					
					$(this).click(function(){
						var value = inputValueArray;
						var linktext = $(this).text();
						if ($(value).index(linktext) >= 0) {
							owner.arrayRemove(value, $(this).text());
							$(input).val(value.join(options.seperator));
							owner.setClass(this, normalStyle, normalHoverStyle);
						}
						else {
							value.push(linktext);
							$(input).val(value.join(options.seperator));
							owner.setClass(this, selectedStyle, normalHoverStyle);
						}
						this.blur();
						return false;
					});
				}
			});
		}
	}
    
    $.fn.jTagging = function(tags, seperator){
        var options = {
            tags: tags,
            seperator: seperator,
            style: $.jTagging.defaults
        }
		var tagHelpr=new $.jTagging(this,options);
    }
})(jQuery);
